/**
 * 全局访问控制，不登录不能访问系统资源，
 * 登录之后获取系统资源访问权限
 */
import router from './router'
import store from './store'
import { MessageBox, Message } from 'element-ui'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import { getToken } from '@/utils/auth' // get token from cookie
import getPageTitle from '@/utils/get-page-title'

NProgress.configure({ showSpinner: false }) // NProgress Configuration

const whiteList = ['/login'] // no redirect whitelist

router.beforeEach(async (to, from, next) => {
  // start progress bar
  NProgress.start()
  // set page title
  document.title = getPageTitle(to.meta.title)
  // determine whether the user has logged in
  const hasToken = getToken()
  if (hasToken) {
    // 有token表明已经登录了,但是还要判断用户信息是否已经获取了,否则用户无法操作
    if (store.getters.name) {
      hasLoggedinAndUserExists(to, from, next);
    } else {
      hasLoggedinButUserNotExists(to, from, next)
    }
  } else {
    isNotLogin(to, from, next);
  }
})

/**
 * 没有登录
 * @param {*} to 
 * @param {*} from 
 * @param {*} next 
 */
function isNotLogin(to, from, next) {
  /* has no token*/
  if (whiteList.indexOf(to.path) !== -1) {
    // in the free login whitelist, go directly
    next()
  } else {
    next(`/login?redirect=/data`)
    NProgress.done()
  }
}

/**
 * 已经登录，用户信息也存在
 * @param {*} to 
 * @param {*} from 
 * @param {*} next 
 */
function hasLoggedinAndUserExists(to, from, next) {
  console.log(store.getters.visitedViews)
  if( to.name == undefined ) {
    next({ path: store.getters.router})
  }else if (to.path === '/login' || to.path === '/') {
    // 如果持有token，并且访问登录页面则直接路由到主页
    next({ path: '/data' })
    NProgress.done()
  } else {
    next()
  }
}
/**
 * 已经登录，单用户信息不存在
 * @param {*} to 
 * @param {*} from 
 * @param {*} next 
 */
async function hasLoggedinButUserNotExists(to, from, next) {
  try {
    // 获取用户信息
    const { permissions } = await store.dispatch('user/getInfo')
    // 基于权限信息生成路由
    const accessRoutes = await store.dispatch(
      'permission/generateRoutes', permissions)
    // dynamically add accessible routes
    //登录成功之后跳转到首页,这里在跳转之前先添加路由，然后再调用next进行跳转
    router.addRoutes(accessRoutes)
    // hack method to ensure that addRoutes is complete
    // set the replace: true, so the navigation will not leave a history record
    // next({ ...to, replace: false })
    //例如在登录的时候还不存在路由，所以被导航到了404
    //但是添加路由之后就应该导航到正确路由，所以应该是to.redirectedFrom
    //如果不是redirect，那么就去to.path，该是什么就是什么
    next({ path: to.redirectedFrom || to.path, replace: false })
  } catch (error) {
    console.log('异常:%o', error)
    //删除token，然后重新登录
    await store.dispatch('user/resetToken')
    // Message.error(error || 'Has Error')
    //next(`/login?redirect=${to.path}`)
    // next(`/login?redirect=/`)
    // NProgress.done()
    NProgress.done()
  }
}

router.afterEach(() => {
  // finish progress bar
  NProgress.done()
})
